package com.partner.druidfilter;

import com.alibaba.druid.filter.FilterChain;
import com.alibaba.druid.filter.FilterEventAdapter;
import com.alibaba.druid.proxy.jdbc.ResultSetProxy;
import com.alibaba.druid.proxy.jdbc.StatementProxy;
import com.alibaba.druid.sql.parser.ParserException;
import com.alibaba.druid.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;

/**
 * @ClassName: SqlCheckFilter
 * @Description:
 * @author: Fighter
 * @date: 2022/10/30 21:36
 **/
@Slf4j
public class SqlCheckFilter extends FilterEventAdapter {

    @Override
    public ResultSetProxy statement_executeQuery(FilterChain chain, StatementProxy statement, String sql) throws SQLException {
        log.info("sql 拦截器: {}", sql);

        if (sql.contains(";")) {
            String[] split = sql.split(";");
            if (split.length >= 2 && !StringUtils.isEmpty(split[1])) {
                log.warn("不允许进行SQL拼接: {}", sql);
                throw new ParserException("illegal sql expr : " + sql);
            }
        }

        if (sql.contains("in")) {
            String[] split = sql.split("in");
            if (split[1].split(",").length > 10) {
                log.warn("SQL语句中in列表超过10个: {}", sql);
                throw new ParserException("illegal sql expr : " + sql);
            }
        }

        return super.statement_executeQuery(chain, statement, sql);
    }
}
